﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using SimpleFMMatrix.DataStructures;

namespace SimpleFMMatrix.ViewModel
{
    public class PianoKeyVM : DependencyObject
    {
        public static readonly DependencyProperty IsPressedProperty =
            DependencyProperty.Register("IsPressed", typeof(bool), typeof(PianoKeyVM),
            new PropertyMetadata(false, (d, e) =>
            {
                var s = (PianoKeyVM)d;
                if ((bool)e.NewValue) s.OnPress();
                else s.OnRelease();
            }));

        public FMMatrix Matrix { get; private set; }
        public PianoKey PianoKey { get; private set; }
        public FMNote Note { get; private set; }

        public bool IsPressed
        {
            get { return (bool)GetValue(IsPressedProperty); }
            set { SetValue(IsPressedProperty, value); }
        }

        protected void OnPress()
        {
            if (Note == null)
            {
                Note = Matrix.Play(440 * Math.Pow(2, (double)(PianoKey.MidiNumber - 69) / 12.0));
            }
        }

        protected void OnRelease()
        {
            if (Note != null)
            {
                Note.Release();
                Note = null;
            }
        }

        public PianoKeyVM(FMMatrix matrix, PianoKey _Key)
        {
            Matrix = matrix;
            PianoKey = _Key;
        }
    }
}
